package main

import (
	"fmt"
	"net"
	"os"
	"time"
)

//config
const requestAddress = "127.0.0.1:8080"       // 请求地址
const serverAddress ="39.106.168.153:8090"         // 服务端地址
const maxDataSize = 1024*1024*10              // 请求最大长度（B）
const errContent = "HTTP/1.1 200 OK\nContent-Type: application/json; charset=utf-8\n\n{\"message\":\"client error\"}"

var serverConn net.Conn
var err error

func checkErrorAndExit(err error,msg string){
	if err != nil{
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
		fmt.Println("出错了",msg,err)
		_=serverConn.Close()
		time.Sleep(10*time.Second)
		os.Exit(1)
	}
}

func main() {
	serverConn, err =net.Dial("tcp", serverAddress)
	if err != nil{
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
		fmt.Println("与服务端连接失败",err)
		time.Sleep(10*time.Second)
		os.Exit(1)
	}
	defer func() {
		_=serverConn.Close()
	}()
	request := make([]byte,maxDataSize)
	response := make([]byte,maxDataSize)
	for{
		requestCnt, err := serverConn.Read(request)
		checkErrorAndExit(err,"接收请求失败")
		requestConn, err :=net.Dial("tcp", requestAddress)
		if err != nil{
			fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
			fmt.Println("与请求地址建立连接失败",err)
			_, err = serverConn.Write([]byte(errContent))
			checkErrorAndExit(err,"转发回复失败")
			continue
		}
		_, err = requestConn.Write(request[:requestCnt])
		if err != nil{
			fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
			fmt.Println("转发请求失败",err)
			_=requestConn.Close()
			_, err = serverConn.Write([]byte(errContent))
			checkErrorAndExit(err,"转发回复失败")
			continue
		}
		responseCnt, err := requestConn.Read(response)
		if err != nil{
			fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
			fmt.Println("接收回复失败",err)
			_=requestConn.Close()
			_, err = serverConn.Write([]byte(errContent))
			checkErrorAndExit(err,"转发回复失败")
			continue
		}
		_, err = serverConn.Write(response[:responseCnt])
		checkErrorAndExit(err,"转发回复失败")
		_=requestConn.Close()
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
		fmt.Println("请求成功!")
	}
}
